<template>
  <div class="container">
    <el-card class="table-card">
      <!-- 表头 -->
      <template #header>
        <div class="card-header">
          <el-icon>
            <List/>
          </el-icon>
          <span>日志列表</span>
        </div>
      </template>

      <!-- 查询表单 -->
      <div class="query-form">
        <el-form :inline="true" :model="queryParams">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item label="方法" style="width: 100%;">
                <el-input v-model="queryParams.method" placeholder="方法名" clearable/>
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <el-form-item label="类型" style="width: 100%;">
                <DictSelect v-model="queryParams.type" dicTypeCode="log_type"/>
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <el-form-item label="操作人" style="width: 100%;">
                <TableDictSelect
                    v-model="queryParams.handler"
                    table-name="app_user"
                    label-field="userCode"
                    value-field="userId"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="开始时间" style="width: 100%;">
                <el-date-picker
                    style="width: 100%;"
                    v-model="queryParams.startTime"
                    type="datetime"
                    placeholder="开始时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    clearable
                    :disabled-date="disabledStartDate"
                />
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <el-form-item label="结束时间" style="width: 100%;">
                <el-date-picker
                    style="width: 100%;"
                    v-model="queryParams.endTime"
                    type="datetime"
                    placeholder="结束时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    clearable
                    :disabled-date="disabledEndDate"
                />
              </el-form-item>
            </el-col>

            <el-col :span="4" class="form-actions">
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 表格 -->
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          height="calc(100vh - 420px)"
          v-loading="loading"
      >
        <el-table-column prop="type" label="类型" width="150">
          <template #default="scope">
            <DictSelect :model-value="scope.row.type" dicTypeCode="log_type" display-only/>
          </template>
        </el-table-column>

        <el-table-column prop="handler" label="处理人" width="150">
          <template #default="scope">
            <TableDictSelect
                v-model="scope.row.handler"
                table-name="app_user"
                label-field="nickName"
                value-field="userId"
                displayOnly
            />
          </template>
        </el-table-column>

        <el-table-column prop="method" label="方法"/>
        <el-table-column prop="description" label="描述" width="300"/>
        <el-table-column prop="startTime" label="执行时间" width="180"/>
        <el-table-column prop="endTime" label="结束时间" width="180"/>
        <el-table-column prop="duration" label="耗时(ms)" width="120"/>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <DictSelect
                :model-value="scope.row.error != null ? 500 : 200"
                dicTypeCode="handle_status"
                display-only
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewLog(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleQuery"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <LogDetail ref="logDetailRef"/>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, watch} from 'vue'
import {List} from '@element-plus/icons-vue'
import {logApi} from '@/api/core'
import TableDictSelect from '@/components/TableDictSelect.vue'
import DictSelect from '@/components/DictSelect.vue'
import LogDetail from '@/views/log/detail.vue'
import type {LogItem, QueryParams} from '@/types/api'

const logDetailRef = ref<InstanceType<typeof LogDetail>>()
const queryParams = ref<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  type: '',
  handler: '',
  method: '',
  startTime: '',
  endTime: ''
})

const tableData = ref<LogItem[]>([])
const total = ref(0)
const loading = ref(false)

// 查询
const fetchTableData = async () => {
  loading.value = true
  try {
    const res = await logApi.page(queryParams.value)
    tableData.value = res.data?.list || []
    total.value = res.data?.total || 0
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.value.pageNum = 1
  fetchTableData()
}

const handlePageChange = (page: number) => {
  queryParams.value.pageNum = page
  fetchTableData()
}

const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    type: '',
    handler: '',
    method: '',
    startTime: '',
    endTime: ''
  }
  fetchTableData()
}

// 点击详情
const viewLog = (row: LogItem) => {
  logDetailRef.value?.openDialog(row)
}

// 时间控件联动
const disabledStartDate = (time: Date) => {
  if (!queryParams.value.endTime) return false
  return time.getTime() > new Date(queryParams.value.endTime).getTime()
}

const disabledEndDate = (time: Date) => {
  if (!queryParams.value.startTime) return false
  return time.getTime() < new Date(queryParams.value.startTime).getTime()
}

// 自动修正时间
watch(() => queryParams.value.startTime, (newStart) => {
  if (newStart && queryParams.value.endTime) {
    if (new Date(newStart).getTime() > new Date(queryParams.value.endTime).getTime()) {
      queryParams.value.endTime = newStart
    }
  }
})

watch(() => queryParams.value.endTime, (newEnd) => {
  if (newEnd && queryParams.value.startTime) {
    if (new Date(newEnd).getTime() < new Date(queryParams.value.startTime).getTime()) {
      queryParams.value.startTime = newEnd
    }
  }
})

onMounted(() => {
  fetchTableData()
})
</script>

<style scoped>
.container {
  display: flex;
  gap: 16px;
  height: 100%;
}

.table-card {
  flex: 1;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.query-form {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  --el-table-border-color: #eaeaea;
}
</style>
